package com.ys.ylideas.config;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.alibaba.druid.wall.WallConfig;
import com.alibaba.druid.wall.WallFilter;
import com.ys.ylideas.YlIdeasApplication;

@Configuration
public class DruidDataSourceConfig {

	 private Logger logger = LoggerFactory.getLogger(YlIdeasApplication.class);

	 @Bean
	 @ConfigurationProperties("spring.datasource")
	 public DataSource writeDataSource() {
		 DruidDataSource datasource = new DruidDataSource();
         List<Filter> filters = new ArrayList<>();
         filters.add(wallFilter);
         datasource.setProxyFilters(filters);
		 return datasource;
     }
	 
	 @Autowired
	 WallFilter wallFilter;
	
	
	 @Bean(name = "wallConfig")
	 WallConfig wallFilterConfig(){
	     WallConfig wc = new WallConfig ();
	     wc.setMultiStatementAllow(true);
	     return wc;
	 }
	
	@Bean(name = "wallFilter")
	@DependsOn("wallConfig")
	WallFilter wallFilter(WallConfig wallConfig){
	    WallFilter wfilter = new WallFilter ();
	    wfilter.setConfig(wallConfig);
	    return wfilter;
	}
	 
	 @Bean
     public ServletRegistrationBean druidStatViewServlet() {
         ServletRegistrationBean registrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
         registrationBean.addInitParameter("allow", "61.144.116.110");// IP白名单 (没有配置或者为空，则允许所有访问)
         registrationBean.addInitParameter("deny", "");// IP黑名单 (存在共同时，deny优先于allow)
         registrationBean.addInitParameter("loginUsername", "yiIdea");
         registrationBean.addInitParameter("loginPassword", "yiIdea");
         registrationBean.addInitParameter("resetEnable", "false");
         return registrationBean;
     }

     @Bean
     public FilterRegistrationBean druidWebStatViewFilter() {
         FilterRegistrationBean registrationBean = new FilterRegistrationBean(new WebStatFilter());
         registrationBean.addInitParameter("urlPatterns", "/*");
         registrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
         return registrationBean;
     }
}
